package com.boctech.yxt.authcenter.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boctech.yxt.authcenter.utils.JwtTokenUtils;
import com.boctech.yxt.commonsutils.exception.AjaxResponse;
import com.boctech.yxt.commonsutils.exception.CustomException;
import com.boctech.yxt.commonsutils.exception.ExceptionType;
import com.boctech.yxt.persistance.entity.SysUser;
import com.boctech.yxt.persistance.mapper.MySystemMapper;
import com.boctech.yxt.persistance.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JwtAuthService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private MySystemMapper systemMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    JwtTokenUtils jwtTokenUtils;


    public Map<String, Object> login(String username, String password) throws CustomException{

        try {
            // 利用认证管理器对用户进行认证，如果密码错误，抛出异常
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            Authentication authentication = authenticationManager.authenticate(authenticationToken);

        } catch (AuthenticationException e) {
            throw new CustomException(ExceptionType.UNAUTHORIZED, "用户名或密码不正确");
        }
        // 获取到用户
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SysUser sysUser = userMapper.selectOne(queryWrapper);

        // 生成token
        String token = jwtTokenUtils.generateToken(sysUser);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", sysUser.getId());
        map.put("username", sysUser.getUsername());
        List<Long> roleIds = systemMapper.selectRoleKeysByUserName(username);
        map.put("rid", roleIds.get(0));
        map.put("email", sysUser.getEmail());
        map.put("mobile", sysUser.getPhone());
        map.put("token", token);

        return map;


    }
}
